<template>
  <view class="practice-container">
    <!-- 顶部进度条 -->
    <view class="progress-header">
      <view class="progress-info">
        <text class="chapter-title">我的错题</text>
        <text class="progress-text">{{ currentIndex + 1 }}/{{ questions.length }}</text>
      </view>
      <view class="progress-bar">
        <view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
      </view>
    </view>

    <!-- 题目卡片 -->
    <view class="question-wrapper">
      <question-card v-if="currentQuestion" :questionData="currentQuestion" :questionIndex="currentIndex + 1"
        :totalQuestions="questions.length" :showDifficulty="true" @select="handleSelectAnswer" @multipleChoiceConfirm="handleMultipleChoiceConfirm"/>
      
      <!-- 空状态提示 -->
      <view v-else-if="!loading && questions.length === 0" class="empty-state">
        <view class="empty-icon">❌</view>
        <text class="empty-text">暂无错题</text>
        <text class="empty-desc">去题库中练习一些题目吧</text>
        <view class="empty-btn" @click="goToBankList">
          <text class="btn-text">去练习题目</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="action-btn" @click="previousQuestion" :class="{ disabled: currentIndex === 0 }">
        <text class="btn-icon">←</text>
        <text class="btn-text">上一题</text>
      </view>

      <view class="action-btn" @click="toggleFavorite">
        <text class="btn-icon">{{ currentQuestion && currentQuestion.isFavorite ? '⭐' : '☆' }}</text>
        <text class="btn-text">收藏</text>
      </view>

      <view class="action-btn show-card-btn" @click="showAnswerCard">
        <text class="btn-icon">📋</text>
        <text class="btn-text">答题卡</text>
      </view>

      <view class="action-btn primary" @click="nextQuestion">
        <text class="btn-icon">→</text>
        <text class="btn-text">{{ isLastQuestion ? '完成' : '下一题' }}</text>
      </view>
    </view>

    <!-- 答题卡组件 -->
    <answer-card :visible="showCard" :questions="answerCardData" :currentIndex="currentIndex" :showSubmit="false"
      @close="showCard = false" @select="handleSelectQuestion" />
  </view>
</template>

<script>
import QuestionCard from '@/components/question-card/question-card.vue'
import AnswerCard from '@/components/answer-card/answer-card.vue'
import { getQuestionDetail } from '@/api/exam/question'
import { addQuestionFavorite, cancelQuestionFavorite } from '@/api/exam/questionFavorite'
import { queryErrorQuestionIdsByBank ,submitErrorAnswer} from '@/api/exam/errorQuestion'

export default {
  components: {
    QuestionCard,
    AnswerCard
  },
  data() {
    return {
      bankId: null, // 题库ID
      currentIndex: 0,
      showCard: false, // 控制答题卡显示
      loading: false, // 加载状态
      questions: [],
      answerCardData: [],
      userAnswers: {}, // 存储用户答案 {questionId: selectedOption}
      questionStartTime: null, // 题目开始时间
      practiceMode: '3' // 练习模式：1顺序刷题 2随机刷题 3错题重练
    }
  },
  onLoad(options) {
    // 获取页面参数
    if (options.bankId) {
      this.bankId = options.bankId
      this.loadWrongQuestionInfo()
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex]
    },
    progressPercent() {
      return ((this.currentIndex + 1) / this.questions.length) * 100
    },
    isLastQuestion() {
      return this.currentIndex === this.questions.length - 1
    },
  },
  methods: {
    // 加载错题信息
    async loadWrongQuestionInfo() {
      if (!this.bankId) {
        uni.showToast({
          title: '缺少题库ID',
          icon: 'none'
        })
        return
      }

      this.loading = true
      uni.showLoading({
        title: '加载中...'
      })

      try {
        const res = await queryErrorQuestionIdsByBank(this.bankId)
        if (res.code === 200) {
          // 处理返回的数据
          if (res.data) {
            if (res.data && res.data.length > 0) {
              // 构建题目列表，只包含基本信息，详细信息需要单独获取
              this.questions = []
              this.answerCardData = []
              for(let item of res.data) {
                this.questions.push({
                  id: item,
                  isFavorite: false // 初始化收藏状态
                })
                this.answerCardData.push({
                  hasAnswered:false,
                  isCorrect:null,
                  questionId:item
                })
              }
              this.currentIndex = 0
              // 如果有第一个未答题的题目ID，获取该题目的详细信息
              await this.loadQuestionDetail(res.data[0])
            }
          }
        } else {
          uni.showToast({
            title: res.msg || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载错题信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },

    // 加载题目详细信息
    async loadQuestionDetail(questionId) {
      try {
        const res = await getQuestionDetail(questionId)
        if (res.code === 200) {
          // 处理题目详细信息
          if (res.data) {
            // 将后端数据转换为前端需要的格式
            const questionData = this.transformQuestionData(res.data)
            // 更新answerCardData中对应题目的数据
            const answerCardIndex = this.answerCardData.findIndex(q => q.questionId === questionId)
            if (answerCardIndex !== -1) {
              //错题页面默认未答题，未正确
              this.answerCardData[answerCardIndex].hasAnswered = false
              this.answerCardData[answerCardIndex].isCorrect = null
            }
            // 如果题目列表为空，添加这个题目
            if (this.questions.length === 0) {
              this.questions.push(questionData)
              this.currentIndex = 0
            } else {
              // 找到该题目在题目列表中的索引
              const questionIndex = this.questions.findIndex(q => q.id === questionId)
              // 如果找到了题目，更新题目数据并定位到该题目
              if (questionIndex !== -1) {
                this.$set(this.questions, questionIndex, questionData)
                this.currentIndex = questionIndex
              } else {
                // 如果没找到，添加到列表末尾
                this.questions.push(questionData)
                this.currentIndex = this.questions.length - 1
              }
            }

            // 记录题目开始时间
            this.questionStartTime = Date.now()
          }
        } else {
          console.error('获取题目详细信息失败:', res.msg)
        }
      } catch (error) {
        console.error('获取题目详细信息异常:', error)
      }
    },

    // 转换题目数据格式
    transformQuestionData(backendData) {
      // 转换选项数据
      const options = backendData.options.map(option => option.optionContent)
      // 找到正确答案的索引
      const correctAnswer = backendData.answers[0]?.answerContent
      const correctIndex = backendData.options.findIndex(option => option.optionLabel === correctAnswer)
      // 构建正确答案索引数组：找出所有 isCorrect === "1" 的选项索引
      const correctIndexList = backendData.options
        .map((option, index) => option.isCorrect === "1" ? index : null)
        .filter(index => index !== null)

      return {
        id: backendData.questionId.toString(),
        type: backendData.questionType,
        difficulty: parseInt(backendData.difficultyLevel) || 1,
        question: backendData.questionTitle,
        code: null,
        options: options,
        correct: correctIndex,
        correctIndexList: correctIndexList,
        easyWrong: null, // 后端数据中没有易错项信息
        explanation: backendData.questionAnalysis || backendData.questionAnalyze || '',
        score: backendData.score || backendData.questionScore || 0,
        tags: backendData.tags || [],
        useCount: backendData.useCount || 0,
        correctCount: backendData.correctCount || 0,
        isFavorite: backendData.isFavorite || false,
        hasAnswered: false,
        isCorrect: false,
        selectedOptions: null

      }
    },

    // 处理选择答案
    async handleSelectAnswer(data) {
      this.userAnswers[data.questionId] = data.selectedOption

      // 计算答题用时
      const answerTime = this.questionStartTime ? Math.floor((Date.now() - this.questionStartTime) / 1000) : 0

      // 构建提交答案的参数
      const submitData = {
        questionId: parseInt(data.questionId),
        bankId: parseInt(this.bankId),
        selectedOptionIds: [data.selectedOption + 1], // 选项ID从1开始，所以+1
        userAnswer: this.getOptionLabel(data.selectedOption), // 选项标签 A,B,C,D等
        answerContent: null, // 主观题答案内容，选择题不需要
        answerTime: answerTime,
        practiceMode: this.practiceMode
      }
      try {
        const res = await submitErrorAnswer(submitData)
        if (res.code === 200) {
          // 可以在这里处理提交成功后的逻辑
        } else {
          console.error('答案提交失败:', res.msg)
          uni.showToast({
            title: '答案提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('答案提交异常:', error)
        uni.showToast({
          title: '答案提交异常',
          icon: 'none'
        })
      }
    },
    // 获取选项标签 (A, B, C, D, E...)
    getOptionLabel(index) {
      if (index === null || index === undefined) return ''
      return String.fromCharCode(65 + index)
    },
    // 上一题
    previousQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
        this.questionStartTime = Date.now() // 记录新题目的开始时间
        const question = this.questions[this.currentIndex]
        if (!question.question) {
          this.loadQuestionDetail(question.id)
        }
      }
    },
    // 下一题
    nextQuestion() {
      if (this.isLastQuestion) {
        this.completePractice()
      } else {
        this.currentIndex++
        this.questionStartTime = Date.now() // 记录新题目的开始时间
        //通过currentIndex获取answerCardData中对应的题目，并更新题目数据
        //首先判断是否已经加载过了
        const question = this.questions[this.currentIndex]
        if (!question.question) {
          this.loadQuestionDetail(question.id)
        }
      }
    },
    // 完成练习
    completePractice() {
      const answeredCount = Object.keys(this.userAnswers).length
      const correctCount = Object.entries(this.userAnswers).filter(
        ([questionId, answer]) => {
          const question = this.questions.find(q => q.id === questionId)
          return question && answer === question.correct
        }
      ).length

      uni.showModal({
        title: '错题练习完成',
        content: `本次错题练习已完成！\n已答题：${answeredCount}/${this.questions.length}\n正确：${correctCount}题`,
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },
    // 显示答题卡
    showAnswerCard() {
      this.showCard = true
    },
    // 从答题卡选择题目
    handleSelectQuestion(index) {
      this.currentIndex = index
      this.questionStartTime = Date.now() // 记录新题目的开始时间
      const question = this.questions[this.currentIndex]
      if (!question.question) {
        this.loadQuestionDetail(question.id)
      }
    },
    // 收藏/取消收藏
    async toggleFavorite() {
      if (!this.currentQuestion) return

      // 保存原始状态，用于错误回滚
      const originalFavoriteState = this.currentQuestion.isFavorite
      const newFavoriteState = !this.currentQuestion.isFavorite

      // 先更新UI状态
      this.currentQuestion.isFavorite = newFavoriteState

      // 更新题目数组中的收藏状态
      const questionIndex = this.questions.findIndex(q => q.id === this.currentQuestion.id)
      if (questionIndex !== -1) {
        this.$set(this.questions, questionIndex, { ...this.currentQuestion })
      }

      // 显示操作提示
      uni.showToast({
        title: newFavoriteState ? '收藏中...' : '取消收藏中...',
        icon: 'loading',
        duration: 1000
      })

      // 调用API保存收藏状态
      const success = await this.saveFavoriteStatus(this.currentQuestion.id, newFavoriteState)

      if (success) {
        // API调用成功，显示成功提示
        uni.showToast({
          title: newFavoriteState ? '已收藏' : '取消收藏',
          icon: 'success'
        })
      } else {
        // API调用失败，回滚状态
        this.currentQuestion.isFavorite = originalFavoriteState
        if (questionIndex !== -1) {
          this.$set(this.questions, questionIndex, { ...this.currentQuestion })
        }
      }
    },
    
    // 保存收藏状态
    async saveFavoriteStatus(questionId, isFavorite) {
      try {
        if (isFavorite) {
          // 添加收藏
          const res = await addQuestionFavorite({
            questionId: questionId
          })
          if (res.code === 200) {
            return true
          } else {
            console.error('收藏失败:', res.msg)
            return false
          }
        } else {
          // 取消收藏
          const res = await cancelQuestionFavorite({
            questionId: questionId
          })
          if (res.code === 200) {
            return true
          } else {
            console.error('取消收藏失败:', res.msg)
            return false
          }
        }
      } catch (error) {
        console.error('保存收藏状态失败:', error)
        return false
      }
    },
    // 笔记
    toggleNote() {
      uni.showToast({
        title: '笔记功能开发中',
        icon: 'none'
      })
    },
    // 设置
    showSettings() {
      uni.showToast({
        title: '设置功能开发中',
        icon: 'none'
      })
    },
    
    // 跳转到题库列表
    goToBankList() {
      uni.navigateBack()
    },
    // 处理多选题确认答案
    async handleMultipleChoiceConfirm(data) {
      const params = {
        questionId: parseInt(data.questionId),
        bankId: parseInt(this.bankId),
        selectedOptionIds: data.selectedOptions.map(option => option + 1),
        userAnswer: data.selectedOptions.map(option => this.getOptionLabel(option)).join(','),
        answerContent: null,
        answerTime: 0,
        practiceMode: this.practiceMode
      }
      try {
        const res = await submitErrorAnswer(params)
        if (res.code === 200) {
          // 判断该题是否正确，使用 $set 更新数组元素，确保响应式更新
          const answerCardItem = this.answerCardData[this.currentIndex]
          this.$set(this.answerCardData, this.currentIndex, {
            ...answerCardItem,
            isCorrect: res.data.isCorrect,
            hasAnswered: true
          })
        } else {
          console.error('答案提交失败:', res.msg)
        }
      } catch (error) {
        console.error('答案提交异常:', error)
        uni.showToast({
          title: '答案提交异常',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.practice-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

.progress-header {
  background: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.chapter-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
}

.progress-bar {
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #ff6b6b, #ee5a52);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.question-wrapper {
  padding: 20rpx 30rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  gap: 15rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 99;
}

.action-btn {
  flex: 1;
  padding: 15rpx 20rpx;
  border-radius: 25rpx;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  gap: 8rpx;
}

.show-card-btn {
  flex: 0.9;
}

.action-btn.primary {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.action-btn.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.action-btn:active {
  transform: scale(0.95);
}

.btn-icon {
  font-size: 24rpx;
}

.btn-text {
  font-size: 24rpx;
  color: #333;
  font-weight: bold;
}

.action-btn.primary .btn-text,
.action-btn.primary .btn-icon {
  color: #fff;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 60rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.empty-btn {
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  border-radius: 25rpx;
  box-shadow: 0 4rpx 15rpx rgba(255, 107, 107, 0.3);
}

.empty-btn .btn-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}
</style>
